import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;

public class ExamStudentListFrame extends JFrame {
    private int examId;
    private String examTitle;
    private User teacher;
    private Exam exam;

    private JTable participatedTable;
    private JTable notParticipatedTable;
    private DefaultTableModel participatedTableModel;
    private DefaultTableModel notParticipatedTableModel;

    private JButton viewPaperButton;
    private JButton refreshButton;
    private JButton closeButton;

    // DAO
    private ExamDAO examDAO;
    private UserDAO userDAO;
    private ExamRecordDAO examRecordDAO;

    public ExamStudentListFrame(int examId, String examTitle, User teacher) {
        this.examId = examId;
        this.examTitle = examTitle;
        this.teacher = teacher;

        // 初始化DAO
        this.examDAO = new ExamDAO();
        this.userDAO = new UserDAO();
        this.examRecordDAO = new ExamRecordDAO();

        // 加载考试信息
        this.exam = examDAO.getExamById(examId);

        initComponents();
        setupLayout();
        setupEvents();
        loadStudentData();
    }

    private void initComponents() {
        setTitle("考试学生管理 - " + examTitle);
        setSize(1200, 800);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setResizable(true);

        // 字体设置
        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 14);

        // 已参与学生表格
        String[] participatedColumns = { "学生ID", "学生姓名", "开始时间", "提交时间", "状态", "得分" };
        participatedTableModel = new DefaultTableModel(participatedColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        participatedTable = new JTable(participatedTableModel);
        participatedTable.setRowHeight(30);
        participatedTable.setFont(fieldFont);
        participatedTable.getTableHeader().setFont(labelFont);
        participatedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 设置已参与表格列宽
        participatedTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        participatedTable.getColumnModel().getColumn(1).setPreferredWidth(120);
        participatedTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        participatedTable.getColumnModel().getColumn(3).setPreferredWidth(150);
        participatedTable.getColumnModel().getColumn(4).setPreferredWidth(100);
        participatedTable.getColumnModel().getColumn(5).setPreferredWidth(80);

        // 未参与学生表格
        String[] notParticipatedColumns = { "学生ID", "学生姓名", "用户名", "邮箱", "手机号" };
        notParticipatedTableModel = new DefaultTableModel(notParticipatedColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        notParticipatedTable = new JTable(notParticipatedTableModel);
        notParticipatedTable.setRowHeight(30);
        notParticipatedTable.setFont(fieldFont);
        notParticipatedTable.getTableHeader().setFont(labelFont);
        notParticipatedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 设置未参与表格列宽
        notParticipatedTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        notParticipatedTable.getColumnModel().getColumn(1).setPreferredWidth(120);
        notParticipatedTable.getColumnModel().getColumn(2).setPreferredWidth(120);
        notParticipatedTable.getColumnModel().getColumn(3).setPreferredWidth(180);
        notParticipatedTable.getColumnModel().getColumn(4).setPreferredWidth(120);

        // 按钮
        Dimension buttonSize = new Dimension(120, 45);
        Font buttonFont = new Font("微软雅黑", Font.BOLD, 16);

        viewPaperButton = new JButton("查看试卷");
        viewPaperButton.setPreferredSize(buttonSize);
        viewPaperButton.setFont(buttonFont);
        viewPaperButton.setBackground(new Color(70, 130, 180));
        viewPaperButton.setForeground(Color.WHITE);

        refreshButton = new JButton("刷新");
        refreshButton.setPreferredSize(buttonSize);
        refreshButton.setFont(buttonFont);
        refreshButton.setBackground(new Color(40, 167, 69));
        refreshButton.setForeground(Color.WHITE);

        closeButton = new JButton("关闭");
        closeButton.setPreferredSize(buttonSize);
        closeButton.setFont(buttonFont);
        closeButton.setBackground(new Color(108, 117, 125));
        closeButton.setForeground(Color.WHITE);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));

        // 顶部信息面板
        JPanel topPanel = createTopPanel();

        // 主要内容面板
        JPanel mainPanel = new JPanel(new GridLayout(1, 2, 15, 0));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 已参与学生面板
        JPanel participatedPanel = createParticipatedPanel();

        // 未参与学生面板
        JPanel notParticipatedPanel = createNotParticipatedPanel();

        mainPanel.add(participatedPanel);
        mainPanel.add(notParticipatedPanel);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        buttonPanel.add(viewPaperButton);
        buttonPanel.add(refreshButton);
        buttonPanel.add(closeButton);

        add(topPanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(new Color(70, 130, 180));
        panel.setPreferredSize(new Dimension(1200, 100));

        // 标题
        JLabel titleLabel = new JLabel("考试学生管理", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);

        // 信息面板
        JPanel infoPanel = new JPanel(new GridLayout(2, 2, 10, 5));
        infoPanel.setBackground(new Color(70, 130, 180));
        infoPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        Font infoFont = new Font("微软雅黑", Font.BOLD, 14);

        JLabel examLabel = new JLabel("考试: " + examTitle);
        examLabel.setFont(infoFont);
        examLabel.setForeground(Color.WHITE);

        JLabel teacherLabel = new JLabel("教师: " + teacher.getRealName());
        teacherLabel.setFont(infoFont);
        teacherLabel.setForeground(Color.WHITE);

        String examTime = "未知";
        if (exam != null && exam.getStartTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            examTime = sdf.format(exam.getStartTime());
        }
        JLabel timeLabel = new JLabel("考试时间: " + examTime);
        timeLabel.setFont(infoFont);
        timeLabel.setForeground(Color.WHITE);

        String totalScore = exam != null ? String.valueOf(exam.getTotalScore()) : "未知";
        JLabel scoreLabel = new JLabel("总分: " + totalScore);
        scoreLabel.setFont(infoFont);
        scoreLabel.setForeground(Color.WHITE);

        infoPanel.add(examLabel);
        infoPanel.add(teacherLabel);
        infoPanel.add(timeLabel);
        infoPanel.add(scoreLabel);

        panel.add(titleLabel, BorderLayout.CENTER);
        panel.add(infoPanel, BorderLayout.EAST);

        return panel;
    }

    private JPanel createParticipatedPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(40, 167, 69), 2),
                "已参与学生",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(40, 167, 69)));

        JScrollPane scrollPane = new JScrollPane(participatedTable);
        scrollPane.setPreferredSize(new Dimension(580, 600));
        scrollPane.setBorder(BorderFactory.createLineBorder(Color.GRAY));

        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createNotParticipatedPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(220, 53, 69), 2),
                "未参与学生",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(220, 53, 69)));

        JScrollPane scrollPane = new JScrollPane(notParticipatedTable);
        scrollPane.setPreferredSize(new Dimension(580, 600));
        scrollPane.setBorder(BorderFactory.createLineBorder(Color.GRAY));

        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private void setupEvents() {
        viewPaperButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewSelectedStudentPaper();
            }
        });

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadStudentData();
            }
        });

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        // 双击查看试卷
        participatedTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    viewSelectedStudentPaper();
                }
            }
        });
    }

    private void loadStudentData() {
        // 清空表格
        participatedTableModel.setRowCount(0);
        notParticipatedTableModel.setRowCount(0);

        // 获取所有学生
        List<User> allStudents = userDAO.getAllStudents();

        // 获取参与此考试的学生记录
        List<ExamRecord> examRecords = examRecordDAO.getExamRecordsByExam(examId);

        // 创建参与学生ID列表
        List<Integer> participatedStudentIds = new ArrayList<>();
        for (ExamRecord record : examRecords) {
            participatedStudentIds.add(record.getStudentId());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        // 填充已参与学生表格
        for (ExamRecord record : examRecords) {
            User student = userDAO.getUserById(record.getStudentId());
            if (student != null) {
                String startTime = record.getStartTime() != null ? sdf.format(record.getStartTime()) : "未开始";
                String submitTime = record.getSubmitTime() != null ? sdf.format(record.getSubmitTime()) : "未提交";
                String status = getStatusText(record.getStatus());
                String score = record.getTotalScore() > 0 ? String.valueOf(record.getTotalScore()) : "未评分";

                Object[] row = {
                        record.getStudentId(),
                        student.getRealName(),
                        startTime,
                        submitTime,
                        status,
                        score
                };
                participatedTableModel.addRow(row);
            }
        }

        // 填充未参与学生表格
        for (User student : allStudents) {
            if (!participatedStudentIds.contains(student.getId())) {
                Object[] row = {
                        student.getId(),
                        student.getRealName(),
                        student.getUsername(),
                        student.getEmail() != null ? student.getEmail() : "",
                        student.getPhone() != null ? student.getPhone() : ""
                };
                notParticipatedTableModel.addRow(row);
            }
        }
    }

    private String getStatusText(String status) {
        switch (status) {
            case "not_started":
                return "未开始";
            case "in_progress":
                return "进行中";
            case "submitted":
                return "已提交";
            case "graded":
                return "已阅卷";
            default:
                return status;
        }
    }

    private void viewSelectedStudentPaper() {
        int selectedRow = participatedTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请在已参与学生列表中选择一个学生！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int studentId = (Integer) participatedTableModel.getValueAt(selectedRow, 0);
        String status = (String) participatedTableModel.getValueAt(selectedRow, 4);

        if (!"已提交".equals(status) && !"已阅卷".equals(status)) {
            JOptionPane.showMessageDialog(this, "该学生还未提交考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 打开试卷查看界面
        new ExamPaperViewFrame(examId, studentId, teacher).setVisible(true);
    }
}